﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using System.Web.Security;
using EmitMapper;
using InnovaApp.Layers.DataLayer;
using InnovaApp.Layers.DomainLayer;
using InnovaApp.Layers.ResourcesLayer.Properties;
using InnovaApp.Portals.MVC4Portal.Models;
using InnovaApp.Portals.MVC4Portal.Models.MetaModels.ContactManagement;
using INNOVACALL.Framework.Common;
using INNOVACALL.Framework.Common.CodeFormatting;
using INNOVACALL.Framework.Common.Models;
using INNOVACALL.Framework.Common.MVCHelpers;

namespace InnovaApp.Portals.MVC4Portal.Controllers
{
	public class Sample_BasicForm_MyProfileController : _Controllers_Base<Sample_BasicForm_MyProfileModel>
	{
		protected override void Initialize(System.Web.Routing.RequestContext requestContext)
		{
			base.eMethodBase = "InnovaApp.Portals.InnovaAppFrontOfficePortal.Controllers.Sample_BasicForm_MyProfileController";
			base.specificCssCollection = new string[] { "_FormCommon.css", "Views/Sample_BasicForm_MyProfile.css", "ClientComponents/CodeFormatting/csharp.css", "ClientComponents/KendoUI/kendo.common.min.css", "ClientComponents/KendoUI/kendo.blueopal.min.css" };
			base.specificJSCollection = null;
			base.dynamicJSCollection = new string[] { "/ScriptsG/inoSample_BasicForm_MyProfileDynamic.js" };
			base.specificJqueryJSCollection = new string[] { "ClientComponents/KendoUI/kendo.web.min.js", "InnovacallJS/Sample_BasicForm_MyProfile/Sample_BasicForm_MyProfile.js" };
			base.externalCSS = null;
			base.Meta.Add(enMeta.Description, Resources.View_Sample_BasicForm_MyProfile_Meta_Description);
			base.Meta.Add(enMeta.Keywords, Resources.View_Sample_BasicForm_MyProfile_OrderWithDetails_Meta_Keywords);
			base.Meta.Add(enMeta.Subject, Resources.View_Sample_BasicForm_MyProfile_OrderWithDetails_Meta_Subject);

			base.Initialize(requestContext);
		}

		[HttpGet, Authorize, CacheManager(enCacheMode.NoCache)] //Manage your cache
		public ActionResult Index()
		{
			//NEVER USES VIEW BAG AGAIN !
			//ViewBag.Message = "Modify this template to kick-start your ASP.NET MVC application.";
			{
				using (DataRepositories _dataContext = new DataRepositories())
				{
                    base.InitView(
                        Resources.View_Sample_SingleControl_DropDownList_PageTitle,
                        Resources.View_Sample_SingleControl_DropDownList_PageMessage,
                        specificCssCollection,
                        specificJSCollection,
                        dynamicJSCollection,
                        specificJqueryJSCollection,
                        jsVariables,
                        externalCSS,
                        Meta,
                        _dataContext,
                        true
                        );

					if (Request.QueryString["ReturnUrl"] != null)
					{
						ContentData.ReturnUrlMessage = Resources.View_Sample_BasicForm_MyProfile_PageMessage_Redirected;
					}

					MembershipUser CurrentUser = Membership.GetUser();

					Contact dbContact = _dataContext.Contact_Rep.Query(x => x.FK_InnoAppUser == (Guid)CurrentUser.ProviderUserKey).FirstOrDefault();

					if (dbContact == null)
					{
						ContentData.Contact = new Models.MetaModels.ContactManagement.Contact_MetaModel();
					}
					else
					{
						ContentData.Contact = ObjectMapperManager.DefaultInstance.GetMapper<Contact, Contact_MetaModel>().Map(dbContact);
					}

					List<SelectListItem> Genres = _dataContext.Genre_Rep.GetAll().OrderBy(x => x.SortIndex).Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = x.Name, Selected = (x.Id == ContentData.Contact.FK_Genre) }).ToList();
					Genres.Insert(0, new SelectListItem() { Value = "-1", Text = string.Empty, Selected = (dbContact == null) });
					ContentData.Contact.Genres = Genres;

					#region Involved code rendering
					INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel InvolvedSourceCode;
					INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel InvolvedSubSourceCode;
					ContentData.InvolvedCode = new InvolvedCodeModel();
					InvolvedSourceCode = new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel();

					#region Views, partials & template editors
					InvolvedSourceCode.TabStripName = "Views, partials & template editors";
					InvolvedSourceCode.TabStripContent = string.Empty;
					InvolvedSourceCode.Language = enCodeLanguage._MultipleCodes;

					InvolvedSubSourceCode = new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Html, TabStripName = "View", TabStripContent = "/Views/Sample_BasicForm_MyProfile/Index.cshtml" };
					InvolvedSourceCode.SubCodes.Add(InvolvedSubSourceCode);

					InvolvedSubSourceCode = new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Html, TabStripName = "Layout", TabStripContent = "/Views/Shared/_Layout.cshtml" };
					InvolvedSourceCode.SubCodes.Add(InvolvedSubSourceCode);


					ContentData.InvolvedCode.Add(InvolvedSourceCode);
					#endregion

					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.cSharp, TabStripName = "Controller", TabStripContent = "/Controllers/Sample_BasicForm_MyProfileController.cs" });

					ContentData.InvolvedCode.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.cSharp, TabStripName = "Model", TabStripContent = "/Models/DropDownListModel.cs" });

					#region Javascripts
					InvolvedSourceCode = new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel();
					InvolvedSourceCode.TabStripName = "Javascripts";
					InvolvedSourceCode.TabStripContent = string.Empty;
					InvolvedSourceCode.Language = enCodeLanguage._MultipleCodes;
					InvolvedSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Javascript, TabStripName = "View JS", TabStripContent = "/Scripts/InnovacallJS/Sample_BasicForm_MyProfile/Sample_BasicForm_MyProfile.js" });
					InvolvedSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Javascript, TabStripName = "Layout JS", TabStripContent = "/Scripts/InnovacallJS/_Layout/_Layout.js" });
					ContentData.InvolvedCode.Add(InvolvedSourceCode);
					#endregion

					#region CSS
					InvolvedSourceCode = new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel();
					InvolvedSourceCode.TabStripName = "CSS";
					InvolvedSourceCode.TabStripContent = string.Empty;
					InvolvedSourceCode.Language = enCodeLanguage._MultipleCodes;
					InvolvedSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Css, TabStripName = "View CSS", TabStripContent = "/Content/Views/Sample_BasicForm_MyProfile.css" });
					InvolvedSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Css, TabStripName = "Form Common CSS", TabStripContent = "/Content/_FormCommon.css" });
					InvolvedSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Css, TabStripName = "Site (Layout) CSS", TabStripContent = "/Content/_Site.css" });
					ContentData.InvolvedCode.Add(InvolvedSourceCode);
					#endregion

					#region Generated client files
					InvolvedSourceCode = new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel();
					InvolvedSourceCode.TabStripName = "Generated client files";
					InvolvedSourceCode.TabStripContent = string.Empty;
					InvolvedSourceCode.Language = enCodeLanguage._MultipleCodes;

					InvolvedSubSourceCode = new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel();
					InvolvedSubSourceCode.TabStripName = "Javascript";
					InvolvedSubSourceCode.TabStripContent = string.Empty;
					InvolvedSubSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.cSharp, TabStripName = "Controller", TabStripContent = "/Controllers/ScriptsGController.cs" });
					InvolvedSubSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Html, TabStripName = "View", TabStripContent = "/Views/ScriptsG/inoSample_BasicForm_MyProfileDynamic.cshtml" });
					InvolvedSubSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.GeneratedJavascript, TabStripName = "Generated javascript", TabStripContent = "/ScriptsG/inoSample_BasicForm_MyProfileDynamic.js" });
					InvolvedSourceCode.SubCodes.Add(InvolvedSubSourceCode);

					InvolvedSubSourceCode = new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel();
					InvolvedSubSourceCode.TabStripName = "CSS";
					InvolvedSubSourceCode.TabStripContent = string.Empty;
					InvolvedSubSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.cSharp, TabStripName = "Controller", TabStripContent = "/Controllers/CSSGController.cs" });
					InvolvedSubSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.Html, TabStripName = "View", TabStripContent = "/Views/CSSG/site.cshtml" });
					InvolvedSubSourceCode.SubCodes.Add(new INNOVACALL.Framework.Common.Models.MetaModels.CodeFile_MetaModel() { Language = enCodeLanguage.GeneratedCss, TabStripName = "Generated CSS (from _site.css)", TabStripContent = "/CSSG/Site.css" });
					InvolvedSourceCode.SubCodes.Add(InvolvedSubSourceCode);

					ContentData.InvolvedCode.Add(InvolvedSourceCode);
					#endregion

					RenderCodeFiles(ContentData.InvolvedCode);
					#endregion
				}
				return View(ContentData);
			}
		}

		[HttpPost, Authorize, CacheManager(enCacheMode.NoCache)]
		public JsonResult Index(Sample_BasicForm_MyProfileModel model)
		{
			string eMethod = eMethodBase + "Index[Post]";
			string returnToUrl = Request.QueryString["ReturnUrl"];
			string scriptToExecute = string.Empty;
			object eParameters = new { @modelContactId = model.Contact.Id, @modelContactFK_Genre = model.Contact.FK_Genre, @modelContactFirstName = model.Contact.FirstName, @modelContactLastName = model.Contact.LastName };
			JsonResult toReturn = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };

			using (TransactionScope TS = new TransactionScope())
			{
				try
				{
					using (DataRepositories _dataContext = new DataRepositories())
					{
						Guid currentUserId = (Guid)Membership.GetUser().ProviderUserKey;
						Contact dbContact = _dataContext.Contact_Rep.Query(x => x.FK_InnoAppUser == currentUserId).FirstOrDefault();
						if (dbContact == null)
						{
							dbContact = new Contact();
							dbContact.FK_InnoAppUser = currentUserId;
						}
						dbContact.FK_Genre = model.Contact.FK_Genre;
						dbContact.FirstName = model.Contact.FirstName;
						dbContact.LastName = model.Contact.LastName;
						_dataContext.Contact_Rep.AddUpdate(dbContact);
						_dataContext.Save();
						TS.Complete();
					}
					if (!string.IsNullOrEmpty(returnToUrl))
					{
						scriptToExecute = "$.fn.NavigateTo('" + returnToUrl + "')";
					}
					toReturn.Data = new { @success = true, @scriptToExecute = scriptToExecute, @divToUpdate = string.Empty };
					return toReturn;
				}
				catch (Exception ex)
				{
					TS.Dispose();
					throw ex;
				}
			}
		}
	}
}
